import java.net.*;
import java.io.*;
import java.util.*;

import javax.xml.parsers.*;

public class email_test {
	private URL source;
	private String sessionid;
	private String cookieval;
	private String token;
	private String username;
	private String password;
	private static final String folderinfo = "http://software.nju.edu.cn:8000/cgi-bin/disp_folder_info?uid=";
	private static final String listmail = "http://software.nju.edu.cn:8000/cgi-bin/listmail?folder=Inbox&search=no&sort=dtr&pg=";
	private static final String readbody = "http://software.nju.edu.cn:8000/cgi-bin/readbody?folder=inbox&msg=";
	private ArrayList<mail> emails = new ArrayList<mail>();

	public  void run() throws Exception {
		try {
			email_test test = new email_test();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					System.in));
			System.err.print("Username: ");
			test.username = br.readLine();
			System.err.print("Password: ");
			test.password = br.readLine();
			test.post();
			test.post2();
			test.post3();
			test.listfolder();
			test.listmail();
			test.getxml();
		} catch (IOException ex) {
			System.err.println("A system or network error has occured");
			System.exit(1);
		}
	}

	private void post() throws IOException { // Initial attempt: Get cookie
		source = new URL("http://software.nju.edu.cn:8000/cgi-bin/login");
		HttpURLConnection conn = (HttpURLConnection) source.openConnection();
		conn.setRequestMethod("POST"); // Make a POST request
		conn.setDoOutput(true);
		StringBuffer buf = new StringBuffer();
		buf.append("LoginName=" + this.username + "@software.nju.edu.cn");
		buf.append("&Password=" + this.password);
		OutputStream os = conn.getOutputStream();
		os.write(buf.toString().getBytes());
		os.close();
		conn.connect();
		// System.err.println(conn.getResponseCode());
		cookieval = conn.getHeaderField("Set-Cookie"); // Store cookie
		sessionid = "";
		if (cookieval != "")
			sessionid = cookieval.substring(0, cookieval.indexOf(";"));
	}

	private void post2() throws IOException { // Second attempt: Get token
		HttpURLConnection conn = (HttpURLConnection) source.openConnection();
		if (sessionid != "")
			conn.setRequestProperty("Cookie", sessionid);
		conn.connect();
		/*
		 * String cookieval = conn.getHeaderField("Set-Cookie"); String
		 * sessionid = ""; if (cookieval != null) { if (!cookieval.equals("")) {
		 * sessionid = cookieval.substring(0, cookieval.indexOf(";"));
		 * this.cookieval = cookieval; this.sessionid = sessionid; } }
		 */
		// System.err.println(conn.getResponseMessage());
		BufferedReader br = new BufferedReader(new InputStreamReader(conn
				.getInputStream(), "GBK"));
		String cur = br.readLine();
		while (cur != null) {
			if (cur.contains("token=")) { // Validates if logged in correctly or
											// not
				this.token = cur.substring(7, cur.length() - 2);
				break;
			}
			cur = br.readLine();
		}
		if (token == null) { // If not logged in, exits
			System.err.println("Invaild username or password");
			System.exit(1);
		}
	}

	private void post3() throws IOException { // The real process
		source = new URL("http://software.nju.edu.cn:8000/cgi-bin/login?token="
				+ token);
		HttpURLConnection conn = (HttpURLConnection) source.openConnection();
		if (sessionid != "")
			conn.setRequestProperty("Cookie", sessionid);
		conn.setRequestProperty("Referer",
				"http://software.nju.edu.cn:8000/cgi-bin/login?token=" + token);
		conn.connect();
		// System.err.println(conn.getResponseMessage());
	}

	private void listfolder() throws IOException {
		int total = 0, unread = 0;
		URL url = new URL(folderinfo + this.username
				+ "&domain=software.nju.edu.cn");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestProperty("Cookie", this.sessionid);
		conn.connect();
		InputStream stream = conn.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(stream));
		String cur = "";
		boolean totalf = false;
		while (br.ready()) {
			cur = br.readLine();
			if (cur.contains("tblcautionfont")) { // Header of each folder's
													// HTML
				// TODO Need expansion; this is limited to "Inbox" only
				if (!totalf) {
					totalf = true;
					total = Integer.parseInt(cur.split("<")[1].substring(28,
							cur.split("<")[1].length()));
				} else {
					unread = Integer.parseInt(cur.split("<")[1].substring(29,
							cur.split("<")[1].length()));
				}
			}
		}
		System.out.println("Total: " + total);
		System.out.println("Unread: " + unread);
	}

	private void listmail() throws IOException {
		URL url = new URL(listmail + "0"); // TODO Multiple pages support needed
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestProperty("Cookie", this.sessionid);
		conn.connect();
		InputStream stream = conn.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(stream,
				"GBK"));
		String cur = "";
		boolean incell = false;
		boolean hasattachment = false;
		String curID = "";
		String curtitle = "";
		String cursender = "";
		String curdate = "";
		while (br.ready()) { // Identify the identifiers of each line and seek
								// for useful information
			cur = br.readLine();
			if (cur.contains("libtblnormalcellbg")
					|| cur.contains("libtblleft1cellbg")) // At the head of each
															// mail
				incell = true;
			if (incell) {
				if (cur.contains("MSG.")) { // Message number - will be used
											// when retrieving contents
					curID = cur.split("value=")[1].substring(1, cur
							.split("value=")[1].length() - 2);
					continue;
				}
				if (cur.contains("32%")) { // Sender of this particular email
					cursender = cur.split(">")[2].substring(0,
							cur.split(">")[2].length() - 3);
					cursender = process(cursender);
					continue;
				}
				if (cur.contains("14%")) { // Date sent
					curdate = cur.split(">")[1].substring(0, cur.split(">")[1]
							.length() - 4);
					curdate = process(curdate);
					continue;
				}
				if (cur.contains("33%")) { // Mail's subject
					curtitle = cur.substring(16, cur.length() - 4);
					curtitle = process(curtitle);
					continue;
				}
				if (cur.contains("9%")) {
					if (cur.contains("attachsign.gif"))
						hasattachment = true;
					mail curmail = new mail(cursender, curtitle, curdate,
							hasattachment);
					curmail.setID(curID);
					this.emails.add(curmail); // All information has been
												// gathered, to next one
					incell = false;
					curID = "";
					curtitle = "";
					cursender = "";
					curdate = "";
					hasattachment = false;
					continue;
				}
			}
		}
		for (int i = 0; i < this.emails.size(); i++){
			System.out.println(emails.get(i).toString());
		}
		
	}

	private String process(String str) { // TODO Need expansion
		String tobereturned = str.replace("&nbsp;", " ");
		tobereturned = tobereturned.replace("&lt;", "<");
		tobereturned = tobereturned.replace("&gt;", ">");
		tobereturned = tobereturned.replace("&quot;", "");
		return tobereturned;
	}

	public void getxml() throws IOException, Exception{
		//writexml myxml;
		writexml myxml=new   writexml("D:\\email.xml");
		for (int i = 0; i < emails.size(); i++) {
			StringBuffer document = new StringBuffer();
			try {
				URL url = new URL(readbody + emails.get(i).getID()
						+ "&charset=gb2312");
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setRequestProperty("Cookie", this.sessionid);
				conn.connect();
				InputStream stream = conn.getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(stream,"GBK"));
				String line = null;
				while (!(line = reader.readLine()).contains("</html>"))
					document.append(line + "\n");
				reader.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			String str = document.toString();
			String strDir = "D:\\text";
			String strFile = "test" + i + ".txt";
			File myFile = new File(strDir + "\\" + strFile);

			try {
				myFile.createNewFile();
				BufferedWriter bw = new BufferedWriter(new FileWriter(myFile
						.getPath(), false));
				bw.write(str);
				bw.flush();
				bw.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			String content = null;
			try {
				BufferedReader br = new BufferedReader(new FileReader(myFile));

				String line = null;
				StringBuilder text = new StringBuilder();

				while ((line = br.readLine()) != null) {
					text.append(line);
				}
				br.close();
				
				content = text.toString();
				content = content.replaceAll("<div>", "\r\n").replaceAll(
						"</div>", "\r\n").replaceAll("<p>", "\r\n").replaceAll(
						"</p>", "\r\n").replaceAll("&#160;", " ").replaceAll(
						"<br>", "\r\n").replaceAll("<br>", "\r\n").replaceAll(
						"<a href=\"", "").replaceAll("target=\"_blank\">", "")
						.replaceAll("<[^>]*>", "");
                content=content.replace(" eYou read mail  330) {		window.top.content.document.getElementById(\"content_frame\").height = letter_height + \"px\";	};}//--> BLOCKQUOTE{margin-Top: 0px; margin-Bottom: 0px; margin-Left: 2em}; 						   body{FONT-SIZE:12pt; FONT-FAMILY:&#23435;&#20307;,serif;}; 						   body{font-size: 14px;}", "");
				content=content.replace(" eYou read mail  330) {		window.top.content.document.getElementById(\"content_frame\").height = letter_height + \"px\";	};}//-->body{font-size: 14px;}", "");
				content=content.replace(" eYou read mail  330) {		window.top.content.document.getElementById(\"content_frame\").height = letter_height + \"px\";	};}//-->", "");
				BufferedWriter input = new BufferedWriter(new FileWriter(myFile
						.getPath(), false));
				input.write(content);
				input.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    int myi=i;
		    String myisread="False";
		    boolean myhasattachment=emails.get(i).getHasattachment();
		    String mytitle=emails.get(i).getSubject();
		    String mydate=emails.get(i).getDate();
		    String myintro=content.substring(0, 10);
		    String mycontent=content;
		   
		    myxml.toWrite(myi,myisread,myhasattachment,mytitle,mydate, myintro, mycontent);     
		}
		myxml.toSave(); 
	}
}
